/**
 * Edit window for ORM object field 
 */
Ext.define('app.crud.orm.FieldWindow', {
	extend: 'Ext.window.Window',	
	objectName:null,
	fieldName:null,
	dataForm:null,
	objectList:null,
	uniqueData:null,

	dictionaryUrl:null,
	
	 constructor: function(config) {
			config = Ext.apply({
				modal: true,
		        layout:'fit',
		        width: app.checkWidth(380),
		        height:app.checkHeight(380), 
		        closeAction: 'destroy',
		        tools:app.windowToolsElements()
		    }, config);		
		this.callParent(arguments);
	},
	
	/**
	 * @todo fix columns menu
	 */
	initComponent:function(){

		this.fieldDictionaries = Ext.create('Ext.form.field.ComboBox',{
			name:'dictionary',
			fieldLabel:appLang.DICTIONARY,
			queryMode:'local',
			displayField:'title',
	    	forceSelection:true,
			valueField:'id',
			store:Ext.create('Ext.data.Store',{
				model:'app.comboStringModel',
				autoLoad:true,
				proxy: {
					type: 'ajax',
					url:this.dictionaryUrl + 'list',
					reader: {
			            type: 'json',
			            root: 'data',
			            idProperty: 'id'
			        }
	  		    },
				remoteSort:false,
				sorters: [{
					property : 'title',
					direction: 'ASC'
				}]
			})
		});
		
		this.fieldDefaultNum = Ext.create('Ext.form.field.Number',{
			name:'db_default',
			disabled:true,
			hidden:true,
			fieldLabel:appLang.DEFAULT
		});
		
		this.fieldDefaultString = Ext.create('Ext.form.field.Text',{
			name:'db_default',
			fieldLabel:appLang.DEFAULT
		});
		
		this.fieldLen = Ext.create('Ext.form.field.Number',{
			 name:'db_len',
       	  	 fieldLabel:appLang.DB_LENGTH,
       	  	 allowDecimals:false,
       	  	 value:1,
       	  	 minValue:1
		});
		
		this.fieldScale = Ext.create('Ext.form.field.Number',{
			 name:'db_scale',
		   	 fieldLabel:appLang.DB_SCALE,
      	  	 allowDecimals:false,
      	  	 minValue:0,
      	  	 value:1
		});
		
		this.fieldPrecision = Ext.create('Ext.form.field.Number',{
			 name:'db_precision',
		  	 fieldLabel:appLang.DB_PRECISION,
     	  	 allowDecimals:false,
     	  	 minValue:0,
     	  	 value:0
		});
		
		this.fieldType = Ext.create('Ext.form.field.ComboBox',{
      	  xtype:'combo',
    	  name:'db_type',
    	  fieldLabel:appLang.DB_TYPE,
    	  queryMode:'local',
    	  forceSelection:true,
    	  displayField:'text',
    	  valueField:'id',
    	  store:Ext.create('Ext.data.Store',{
    		  model:'app.comboStringModel',
    		  remoteSort:false,
  		      sorters: [{
		                property : 'text',
		                direction: 'ASC'
		      }]
    	  }),
    	  listeners:{
    		  select:function(field , value , options){
    			  this.dbTypeSelected(field.getValue());
    		  },
    		  scope:this
    	  }
		});
		
		this.fieldLinkType = Ext.create('Ext.form.RadioGroup', {
  			fieldLabel: appLang.LINK_TYPE,
            columns: 2,
            hidden:true,
            items: [
                  {boxLabel: appLang.SINGLE, name: 'link_type',  inputValue: 'object', checked: true,
                	  listeners:{
		            	  'change':{
		            		  fn:function( field, newValue, oldValue, options ){
		            			  if(newValue){
		            				  this.processFields(
		            						  [
			            				          this.fieldDefaultString,
			            				          this.fieldDefaultNum,
			            				          this.fieldType,
			            				          this.fieldLen,
			            				          this.fieldScale,
			            				          this.fieldPrecision,
			            				          this.fieldUnsigned,
			            				          this.fieldAllowHtml,
			            				          this.fieldIsSearch,
			            				          this.fieldDictionaries
		            				           ],[
		            				              this.fieldObject,
		            				              this.fieldRequired
		            				           ]
		            				  );
		            			  }
		            		  },
		            		  scope:this
		            	  }
		              }},
                  {boxLabel: appLang.MULTY, name: 'link_type', inputValue: 'multy',
                	  listeners:{
		            	  'change':{
		            		  fn:function( field, newValue, oldValue, options ){
		            			  if(newValue){
		            				  this.processFields(
		            						  [
			            				          this.fieldDefaultString,
			            				          this.fieldDefaultNum,
			            				          this.fieldType,
			            				          this.fieldLen,
			            				          this.fieldScale,
			            				          this.fieldPrecision,
			            				          this.fieldUnsigned,
			            				          this.fieldAllowHtml,
			            				          this.fieldIsSearch,
			            				          this.fieldDictionaries
		            				           ],[
		            				              this.fieldObject,
		            				              this.fieldRequired
		            				           ]
		            				  );
		            			  }
		            		  },
		            		  scope:this
		            	  }
		              }},
                  {
                	  boxLabel: appLang.DICTIONARY,
                	  name: 'link_type',
                	  inputValue: 'dictionary',
                	  listeners:{
		            	  'change':{
		            		  fn:function( field, newValue, oldValue, options ){
		            			  if(newValue){
		            				  this.processFields(
		            						  [
			            				          this.fieldDefaultString,
			            				          this.fieldDefaultNum,
			            				          this.fieldType,
			            				          this.fieldLen,
			            				          this.fieldScale,
			            				          this.fieldPrecision,
			            				          this.fieldUnsigned,
			            				          this.fieldAllowHtml,
			            				          this.fieldIsSearch,
			            				          this.fieldObject,
			            				          this.fieldRequired,
			            				          this.fieldIsNull
		            				           ],[
		            				              this.fieldDictionaries,
		            				              this.fieldRequired
		            				           ]
		            				  );
		            			  }
		            		  },
		            		  scope:this
		            	  }
		              }
                  }
            ]
  		 });
		
		this.fieldObject = Ext.create('Ext.form.field.ComboBox',{
      	  xtype:'combo',
    	  name:'object',
    	  hidden:true,
    	  fieldLabel:appLang.OBJECT,
    	  queryMode:'local',
    	  valueField:'id',
    	  forceSelection:true,
    	  displayField:'title',
    	  store:Ext.create('Ext.data.Store',{
    		  model:'app.comboStringModel',
    		  data:this.objectList,
    		  remoteSort:false,
  		      proxy: {
  		    	  type: 'ajax'
  		      }
    	  })
		});
		
		this.fieldIsNull = Ext.create('Ext.form.field.Checkbox',{
      	  xtype:'checkbox',
    	  name:'db_isNull',
    	  fieldLabel:appLang.IS_NULL 
		});
		
		this.fieldRequired = Ext.create('Ext.form.field.Checkbox',{
      	  xtype:'checkbox',
    	  name:'required',
    	  fieldLabel:appLang.REQUIRED
		});
		
		this.fieldUnsigned = Ext.create('Ext.form.field.Checkbox',{
	      	xtype:'checkbox',
	    	name:'db_unsigned',
	    	fieldLabel:appLang.DB_UNSIGNED
		});
		
		this.fieldAllowHtml = Ext.create('Ext.form.field.Checkbox',{
	      	xtype:'checkbox',
	    	name:'allow_html',
	    	fieldLabel:appLang.ALLOW_HTML
		});
		
		this.fieldIsSearch = Ext.create('Ext.form.field.Checkbox',{
	      	xtype:'checkbox',
	    	name:'is_search',
	    	fieldLabel:appLang.IS_SEARCH
		});
		
		this.fieldUnique = Ext.create('Ext.form.field.Text',{
			name:'unique',
			fieldLabel:appLang.UNIQUE_GROUP
		});

		this.dataForm = Ext.create('Ext.form.Panel',{
				   bodyPadding:3,
				   frame:false,
				   bodyCls:'formBody',
				   bodyBorder:false,
				   border:false,
				   autoScroll:true,
				   fieldDefaults: {
			           labelWidth: 90,
			           labelAlign:'left',
			           anchor:'100%'
			       },				 
			       items:[
				          {
				        	  xtype:'textfield',
				        	  name:'name',
				        	  fieldLabel:appLang.FIELD_NAME,
				        	  allowBlank:false,
				        	  vtype:'alphanum'
				          },
				          {
				        	 xtype:'textfield',
				        	 name:'title',
				        	 allowBlank:false,
				        	 fieldLabel:appLang.FIELD_TITLE
				          },
				          this.fieldUnique,
				          {
				              xtype: 'radiogroup',
				              fieldLabel: appLang.FIELD_TYPE,
				              items: [
				                  {
				                	  boxLabel: appLang.FILED_STD, 
				                	  name: 'type',  
				                	  inputValue: '', 
				                	  checked: true,
				                	  listeners:{
						            	  'change':{
						            		  fn:function( field, newValue, oldValue, options ){
						            			  if(newValue){
						            				  this.processFields(
						            						  [
						            						   	this.fieldLinkType,
						            						   	this.fieldObject,
						            						   	this.fieldDictionaries
						            						  ],[
						            				           this.fieldDefaultString,
						            				           this.fieldDefaultNum,
						            				           this.fieldType,
						            				           this.fieldLen,
						            				           this.fieldScale,
						            				           this.fieldPrecision,
						            				           this.fieldUnsigned,
						            				           this.fieldAllowHtml,
						            				           this.fieldIsSearch
						            				          ]
						            				  );
						            				  
						            				  this.dbTypeSelected(this.fieldType.getValue());
						            				  
						            			  }
						            		  },
						            		  scope:this
						            	  }
						              }
				                  },
				                  {
				                	  boxLabel: appLang.LINK, 
				                	  name: 'type', 
				                	  inputValue: 'link',
				                	  listeners:{
						            	  'change':{
						            		  fn:function( field, newValue, oldValue, options ){
						            			  if(newValue){
						            				  this.processFields(
						            						  [
							            				          this.fieldDefaultString,
							            				          this.fieldDefaultNum,
							            				          this.fieldType,
							            				          this.fieldLen,
							            				          this.fieldScale,
							            				          this.fieldPrecision,
							            				          this.fieldUnsigned,
							            				          this.fieldAllowHtml,
							            				          this.fieldIsSearch,
							            				          this.fieldDictionaries
						            				           ],[
						            				              this.fieldLinkType,
						            				              this.fieldObject,
						            				              this.fieldRequired
						            				           ]
						            				  );
						            			  }
						            		  },
						            		  scope:this
						            	  }
						              }
				                  }
				              ]
				          },
				          this.fieldLinkType,
				          this.fieldObject,
				          this.fieldType,
				          this.fieldLen ,
				          this.fieldScale,
				          this.fieldPrecision,
				          this.fieldDefaultNum,
				          this.fieldDefaultString,
				          this.fieldIsNull,
				          this.fieldUnsigned,
				          this.fieldAllowHtml,
				          this.fieldIsSearch,
				          this.fieldRequired,
				          this.fieldDictionaries
				   ]
		});
		
		if(app.crud.orm.canEdit){
			this.buttons =[
			     {
			    	text:appLang.SAVE,
			    	scope:this,
			    	handler:this.saveAction
			     },
			     {
			    	text:appLang.CANCEL,
			    	scope:this,
				    handler:this.close
			     }
			];
		}
		
		this.items = [this.dataForm];
		
		this.addEvents(
	            /**
	             * @event dataSaved
	             */
	           'dataSaved'
	    ); 
		
		this.dbTypeSelected('boolean');
		
		if(this.objectName && this.fieldName){
			var handle = this;
			this.on('show' , function(){				
				var params = Ext.apply({object:this.objectName,field:this.fieldName});				
				this.dataForm.getForm().load({
					url:app.crud.orm.Actions.loadObjField,
					params:params,
					scope:this,
					waitMsg:appLang.LOADING,
					success: function(form, action){	
		   		 		if(!action.result.success){
		   		 			Ext.Msg.alert(appLang.MESSAGE, action.result.msg);
		   		 		}else{
		   		 			if(action.result.data.type == 'link'){
		   		 				if(action.result.data.link_config.link_type == "dictionary"){
			   		 				this.fieldDictionaries.setValue(action.result.data.link_config.object);
		   		 				}
		   		 			}else{
		   		 				handle.dbTypeSelected(handle.fieldType.getValue());
		   		 			}
		   		 		}
		   	        },
		   	        failure: app.formFailure
				});				
			},this);
		 }
		
		this.callParent(arguments);
	},
	setTableEngine:function(engine){
		switch (engine) {
			case 'Memory':
				this.fillDbTypesStore([
				                       app.crud.orm.intTypes,
				                       app.crud.orm.floatTypes,
				                       app.crud.orm.charTypes,
				                       app.crud.orm.dateTypes
				                      ]);
				break;
	
			default:
				this.fillDbTypesStore([
				                       app.crud.orm.intTypes,
				                       app.crud.orm.floatTypes,
				                       app.crud.orm.charTypes,
				                       app.crud.orm.dateTypes,
				                       app.crud.orm.textTypes,
				                       app.crud.orm.blobTypes
				                      ]);
				break;
		}
	},
	fillDbTypesStore:function(arrayTypes){
		var data = [];
		Ext.each(arrayTypes, function(types){
			Ext.each(types, function(type){
				data.push({id:type,text:type});
			});
		});
		this.fieldType.getStore().loadData(data,false);
	},
	saveAction:function(){
		var handle = this;
		
		this.dataForm.getForm().submit({
			clientValidation: true,
			waitMsg:appLang.SAVING,
			method:'post',
			url:app.crud.orm.Actions.saveObjField,
			params:{'objectName':this.objectName,'objectField':this.fieldName},
			success: function(form, action) {	
   		 		if(!action.result.success){
   		 			Ext.Msg.alert(appLang.MESSAGE, action.result.msg);
   		 		} else{
   		 			handle.fireEvent('dataSaved');		 
   		 			handle.close();
   		 		}
   	        },
   	        failure: app.formFailure
   	    });
	},
	/**
	 * @param [Array] hide - fields to hide
	 * @param [Array] show - fields to show
	 * @returs void
	 */
	processFields:function(hide , show){
		
		Ext.each(hide,function(item){
			item.disable();
			item.hide();
		});
		
		Ext.each(show,function(item){
			item.enable();
			item.show();
		});	
	},
	dbTypeSelected:function(value){
		if(value == 'boolean'){
			this.processFields(
					[this.fieldIsSearch,this.fieldAllowHtml,this.fieldUnsigned,this.fieldDefaultString , this.fieldLen, this.fieldScale ,this.fieldPrecision,this.fieldRequired, this.fieldIsNull,this.fieldDictionaries],
					[this.fieldDefaultNum]
			);
			return;
		}
		
		if(Ext.Array.indexOf(app.crud.orm.intTypes , value)!=-1){
			this.processFields(
					[this.fieldIsSearch,this.fieldAllowHtml,this.fieldDefaultString ,this.fieldLen ,this.fieldScale,this.fieldPrecision,this.fieldDictionaries],
					[this.fieldDefaultNum,this.fieldRequired,this.fieldUnsigned]
			);
			return;
		}
		
		if(Ext.Array.indexOf(app.crud.orm.floatTypes, value)!=-1){
			this.processFields(
					[this.fieldIsSearch,this.fieldAllowHtml,this.fieldDefaultString, this.fieldLen,this.fieldDictionaries],
					[this.fieldDefaultNum,this.fieldScale,this.fieldPrecision,this.fieldRequired,this.fieldUnsigned ]
			);
			return;
		}
		
		if(Ext.Array.indexOf(app.crud.orm.charTypes, value)!=-1){
			this.processFields(
					[this.fieldDefaultNum, this.fieldScale, this.fieldPrecision,this.fieldUnsigned,this.fieldDictionaries],
					[this.fieldIsSearch,this.fieldAllowHtml,this.fieldDefaultString , this.fieldLen,this.fieldRequired]
			);
			return;
		}
		
		if(Ext.Array.indexOf(app.crud.orm.textTypes, value)!=-1){
			this.processFields(
					[this.fieldLen,this.fieldDefaultNum, this.fieldScale, this.fieldPrecision,this.fieldUnsigned,this.fieldDictionaries],
					[this.fieldIsSearch,this.fieldAllowHtml,this.fieldDefaultString,this.fieldRequired]
			);
			return;
		}
		
		if(Ext.Array.indexOf(app.crud.orm.dateTypes, value)!=-1){
			this.processFields(
					[this.fieldIsSearch,this.fieldAllowHtml,this.fieldLen,this.fieldDefaultNum,this.fieldScale,this.fieldPrecision,this.fieldUnsigned,this.fieldDefaultString,this.fieldDictionaries],
					[this.fieldRequired, this.fieldIsNull]
			);
			return;
		}
	}
});